import fetch from 'isomorphic-fetch';

import API from '../constants/api';
// 请求方式
// let dataWay = '';
console.log('api',API);
// if(API.URL.length == 0){
//   dataWay = 'same-origin';
// }else{
//   dataWay = 'include';
// }

// 超时插件
function _fetch(fetch, timeout) {
  return Promise.race([
      fetch,
      new Promise(function (resolve, reject) {
          setTimeout(() => reject(new Error('request timeout')), timeout);
      })
  ]);
}

export default function ajax(url, type, options, timeout = 50000) {
  if(type == 'get'){
    var optionsNew = '';
    for(let m in options){
      if(optionsNew == ''){
        optionsNew += ('?'+ m +'=' + options[m])
      }else{
        optionsNew += ('&'+ m +'=' + options[m])
      }
    }
    return _fetch(fetch(url + optionsNew,{
      method: "GET",
      credentials: 'same-origin'
    }), timeout).then(function(response) {
      const { dispatch } = store;
      const status = response.status;
      if (response.status >= 200 && response.status < 300) {
        return response;
      }
      const error = new Error(response.statusText);
      error.response = response;
      // message.error(status)
      return false;
      // if (status >= 404 && status < 422) {
      //   dispatch(routerRedux.push('/exception/404'));
      //   throw error;
      // }
      // if (status <= 504 && status >= 500) {
      //   dispatch(routerRedux.push('/exception/500'));
      //   throw error;
      // }
      // if (status === 403) {
      //   dispatch(routerRedux.push('/exception/403'));
      //   throw error;
      // }
    }).then(function(response) {
      return response.json();
    }).catch(function(res) {
      message.error('数据加载失败');
    })
  }else if(type == 'post'){
    return _fetch(fetch(url, {
       method: "POST",
       credentials: 'same-origin',
       headers : {
        'Content-Type': 'application/json'
       },
       body: JSON.stringify(options),
    }), timeout).then(function(response) {
      const { dispatch } = store;
      const status = response.status;
      if (response.status >= 200 && response.status < 300) {
        return response;
      }
      const error = new Error(response.statusText);
      error.response = response;
      // message.error(status)
      return false;
      // if (status >= 404 && status < 422) {
      //   dispatch(routerRedux.push('/exception/404'));
      //   throw error;
      // }
      // if (status <= 504 && status >= 500) {
      //   dispatch(routerRedux.push('/exception/500'));
      //   throw error;
      // }
      // if (status === 403) {
      //   dispatch(routerRedux.push('/exception/403'));
      //   throw error;
      // }
    }).then(function(response) {
      return response.json();
    }).catch(function(res) {
      message.error('数据加载失败');
    })
  }

}
